// app/src/main/java/com/example/snake/SnakeGameActivity.java
package com.example.snake;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.IOException;

public class SnakeGameActivity extends Activity implements GameView.OnGameEventListener {
    private GameView gameView;
    private static final String TAG = "SnakeGameActivity";
    private boolean isPaused = false;
    private boolean isMusicPlaying = false;
    private Button btnPauseResume;
    private TextView tvScore;
    private MediaPlayer mediaPlayer;
    private Button btnSpeed;
    //  在类成员变量区域添加速度相关变量
    private int speedLevel = 1; // 1=慢速, 2=中速, 3=快速,4=超快速
    private static final int[] SPEED_DELAYS = {500, 300, 150,100}; // 不同速度级别的延迟时间
    private ScoreManager scoreManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_snake_game);

        gameView = findViewById(R.id.gameView);
        gameView.setOnGameEventListener(this);
        gameView.startGame();
        // 初始化分数管理器
        scoreManager = new ScoreManager(this);

        // 初始化控制按钮
        initControlButtons();
    }

    private void initControlButtons() {
        Button btnUp = findViewById(R.id.btnUp);
        Button btnDown = findViewById(R.id.btnDown);
        Button btnLeft = findViewById(R.id.btnLeft);
        Button btnRight = findViewById(R.id.btnRight);
        Button btnMusic = findViewById(R.id.btnMusic);
        btnPauseResume = findViewById(R.id.btnPauseResume);
        tvScore = findViewById(R.id.tvScore);
        btnSpeed = findViewById(R.id.btnSpeed);
        // 在 initControlButtons 方法中添加速度按钮点击监听器
        btnSpeed = findViewById(R.id.btnSpeed);
        btnSpeed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeSpeed();
            }
        });
        btnPauseResume.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                togglePauseResume();
            }
        });
        btnUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeDirection(Snake.Direction.UP);
            }
        });

        btnDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeDirection(Snake.Direction.DOWN);
            }
        });

        btnLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeDirection(Snake.Direction.LEFT);
            }
        });

        btnRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeDirection(Snake.Direction.RIGHT);
            }
        });
        btnMusic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initMediaPlayer();
            }
        });
    }

    String[] speedLabels = {"慢速", "中速", "快速"};
    //添加速度切换方法
    private void changeSpeed() {
        // 切换速度级别 (1->2->3->1...)
        speedLevel = (speedLevel % 3) + 1;

        // 更新游戏视图中的速度
        gameView.setSpeedLevel(speedLevel);

        // 更新按钮文本显示当前速度

        btnSpeed.setText("速度: " + speedLabels[speedLevel - 1]);
    }
    // 添加暂停/继续切换方法
    private void togglePauseResume() {
        if (isPaused) {
            // 继续游戏
            gameView.startGame();
            btnPauseResume.setText("暂停");
            isPaused = false;
        } else {
            // 暂停游戏
            gameView.stopGame();
            btnPauseResume.setText("继续");
            isPaused = true;
        }
    }
    private void changeDirection(Snake.Direction newDirection) {
        Snake snake = gameView.getSnake();
        Snake.Direction currentDirection = snake.getDirection();

        // 防止反向移动
        if ((currentDirection == Snake.Direction.UP && newDirection != Snake.Direction.DOWN) ||
                (currentDirection == Snake.Direction.DOWN && newDirection != Snake.Direction.UP) ||
                (currentDirection == Snake.Direction.LEFT && newDirection != Snake.Direction.RIGHT) ||
                (currentDirection == Snake.Direction.RIGHT && newDirection != Snake.Direction.LEFT) ||
                snake.getBody().size() == 1) {
            snake.setDirection(newDirection);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Snake snake = gameView.getSnake();

        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_UP:
                if (snake.getBody().size() == 1 ||
                        snake.getDirection() != Snake.Direction.DOWN) {
                    snake.setDirection(Snake.Direction.UP);
                }
                return true;
            case KeyEvent.KEYCODE_DPAD_DOWN:
                if (snake.getBody().size() == 1 ||
                        snake.getDirection() != Snake.Direction.UP) {
                    snake.setDirection(Snake.Direction.DOWN);
                }
                return true;
            case KeyEvent.KEYCODE_DPAD_LEFT:
                if (snake.getBody().size() == 1 ||
                        snake.getDirection() != Snake.Direction.RIGHT) {
                    snake.setDirection(Snake.Direction.LEFT);
                }
                return true;
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                if (snake.getBody().size() == 1 ||
                        snake.getDirection() != Snake.Direction.LEFT) {
                    snake.setDirection(Snake.Direction.RIGHT);
                }
                return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    // 更新分数显示的方法
    @Override
    public void onScoreChanged(int score) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvScore.setText("分数: " + score);
            }
        });
//        Toast.makeText(this, "得分: " + score, Toast.LENGTH_SHORT).show();
        Log.d("Score", "得分: " + score);
    }


    @Override
    public void onGameOver() {
        int finalScore = gameView.getSnake().getBody().size() - 1;
        // 保存分数
        scoreManager.saveScore(finalScore);

        new AlertDialog.Builder(this)
                .setTitle("游戏结束")
                .setMessage("游戏结束！您的得分是: " + finalScore)
                .setPositiveButton("重新开始", (dialog, which) -> restartGame())
                .setNegativeButton("退出", (dialog, which) -> finish())
                .setCancelable(false)
                .show();
    }

    private void restartGame() {
        setContentView(R.layout.activity_snake_game);
        gameView = findViewById(R.id.gameView);
        gameView.setOnGameEventListener(this);
        gameView.startGame();
        initControlButtons(); // 重新初始化按钮
    }

    private String[] musicFiles = {"周杰伦 - 明明就 [qmms].ogg", "梁静茹 - 会呼吸的痛 [qmms].ogg"}; // 音乐文件
    private int currentSongIndex = 0; // 当前播放的歌曲索引
    private void initMediaPlayer() {
        // 如果mediaPlayer已经存在，先停止并释放它
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.release();
            mediaPlayer = null;
        }
        // 切换到下一首歌曲
        currentSongIndex = (currentSongIndex + 1) % musicFiles.length;
        Log.d(TAG, "切换到歌曲: " + musicFiles[currentSongIndex]);

        try {
            AssetFileDescriptor afd = getAssets().openFd(musicFiles[currentSongIndex]);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            mediaPlayer.prepare();
            Log.d(TAG, "initMediaPlayer");
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 切换播放状态
        if (!mediaPlayer.isPlaying()) {
            mediaPlayer.start();
            isMusicPlaying = true;
            Log.d(TAG, "开始播放音乐");
        } else {
            mediaPlayer.pause(); // 使用pause而不是stop，方便恢复
            isMusicPlaying = false;
            Log.d(TAG, "暂停播放音乐");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (gameView != null) {
            gameView.stopGame();
        }
        // 释放MediaPlayer资源
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}
